package cn.donghuapian.controller;

import cn.donghuapian.service.IUserService;
import cn.donghuapian.vo.ResponseBody;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.expr.MethodCallExpr;
import com.github.javaparser.ast.expr.ObjectCreationExpr;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import com.github.javaparser.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hzw
 * @since 2024-09-26
 */
@RestController
public class TestrController {

    @Autowired
    private IUserService userService;

    /**
     * 统计某个方法在哪里被调用过
     *
     * @return
     */
    @PostMapping("/login")
    public ResponseBody test() throws IOException {
        scanProject(Paths.get("src/main/java/com/yourpackage"));
        return ResponseBody.success();
    }

    public void scanProject(Path projectDir) throws IOException {
        List<Path> javaFiles = Files.walk(projectDir)
                .filter(p -> p.toString().endsWith(".java"))
                .toList();

        for (Path javaFile : javaFiles) {
            scanFile(javaFile);
        }
    }

    private void scanFile(Path javaFile) throws IOException {
        //要统计哪个类的构造函数
        String targetClass = "TestVO";
        JavaParser javaParser = new JavaParser();
        CompilationUnit cu = javaParser.parse(javaFile).getResult().get();

        // 扫描普通方法调用
        cu.findAll(MethodCallExpr.class).forEach(methodCall -> {
            if (methodCall.getNameAsString().equals("methodA")) {
                System.out.println("在文件: " + javaFile);
                System.out.println("位置: " + methodCall.getRange().orElse(null));
                System.out.println("调用参数数量: " + methodCall.getArguments().size());

                // 分析调用参数
                methodCall.getArguments().forEach(arg -> {
                    System.out.println("  参数: " + arg);
                });
                System.out.println("-------------------");
            }
        });

        // 扫描构造方法调用
        cu.findAll(ObjectCreationExpr.class).forEach(constructorCall -> {
            if (constructorCall.getType().asString().equals(targetClass)) {
                int i =  constructorCall.getRange()
                        .map(r -> r.begin.line)
                        .orElse(-1);;
                System.out.println(javaFile + "" + i +"----------" + constructorCall);
            }
        });
    }
}
